package net.martinimix.service.payment.provider.cybersource;

import java.math.BigDecimal;
import java.util.GregorianCalendar;
import java.util.Map;

import net.martinimix.domain.payment.BillMeLaterAccountAuthorization;
import net.martinimix.domain.payment.CreditCardAuthorization;

/**
 * Provides a Bill Me Later CyberSource response adapter.
 * 
 * @author Scott Rossillo
 * 
 * @since 1.1
 *
 */
public class BillMeLaterResponseAdapter extends SimpleCyberSourceResponseAdapter {
	
	/**
	 * Creates a new Bill Me Later response adapter.
	 */
	public BillMeLaterResponseAdapter() { }
	
	/* (non-Javadoc)
	 * @see net.martinimix.service.payment.provider.cybersource.SimpleCyberSourceResponseAdapter#createResponseCommand()
	 */
	protected CreditCardAuthorization createResponseCommand() {
		return new BillMeLaterAccountAuthorization();
	}
	
	/* (non-Javadoc)
	 * @see net.martinimix.service.payment.provider.cybersource.SimpleCyberSourceResponseAdapter#parseAuthorizationResponse(java.util.Map)
	 */
	public CreditCardAuthorization parseAuthorizationResponse(Map reply) {
		
		final BillMeLaterAccountAuthorization auth = (BillMeLaterAccountAuthorization) createResponseCommand();
		final String authAmount = (String) reply.get("ccAuthReply_amount");
		
		auth.setTypeCode("AUT");
		auth.setRequestId( (String) reply.get("requestID") );
		auth.setRequestToken( (String) reply.get("requestToken") );
		auth.setMerchantReferenceCode( (String) reply.get("merchantReferenceCode") );
		auth.setDecision( (String) reply.get("decision") );
		auth.setResponseCode( (String) reply.get("decision") );
		auth.setReasonCode( (String) reply.get("reasonCode") );
		auth.setPositiveResponse(auth.getDecision().equalsIgnoreCase("ACCEPT"));
		auth.setCurrencyCode( (String) reply.get("purchaseTotals_currency") );
		auth.setBankAuthorization( (String) reply.get("ccAuthReply_authorizationCode") );
		
		auth.setStatusCode( auth.isPositiveResponse() ? 
				CreditCardAuthorization.STATUS_SUCCESS : CreditCardAuthorization.STATUS_FAILED );
		
		if(authAmount != null) {
			auth.setAmount(new BigDecimal( authAmount ));
			auth.setAuthorizationDate(parseDate( (String) reply.get("ccAuthReply_authorizedDateTime") ));
		} else {
			auth.setAuthorizationDate(new GregorianCalendar());
		}
		
		if(auth.isPositiveResponse()) {
			auth.setAccountNumber( (String) reply.get("ccAuthReply_bmlAccountNumber") );
		}
		
		return auth;	
	}
	
}
